//
//  TLSearchResultViewController.m
//  WXReader
//
//  Created by huaya on 2025/4/1.
//  Copyright © 2025 Andrew. All rights reserved.
//

#import "TLSearchResultViewController.h"
#import "HMSegmentedControl.h"
#import "TLMallListTableViewCell.h"
#import "TLCategoryNovelTableViewCell.h"

@interface TLSearchResultViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) HMSegmentedControl *segControl;
@property (nonatomic, copy) NSString *searchText;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *datasArray;
@property (nonatomic, strong) NSMutableDictionary *datasDict;

@property (nonatomic, strong) UIView *noDataView;
@property (nonatomic, assign) CGFloat noDataViewHeight;

@property (nonatomic, strong) NSNumber *pageSize;
@property (nonatomic, strong) NSNumber *pageNumb;

@end

@implementation TLSearchResultViewController
- (HMSegmentedControl *)segControl{
    if (!_segControl) {
        _segControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"All",@"Short Story"]];
//        _segControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"All",@"Short Story",@"Novel"]];
        _segControl.backgroundColor = UIColor.clearColor;
        _segControl.titleTextAttributes = @{NSFontAttributeName : MK_FONT_PFSC_Medium(16),
                                            NSForegroundColorAttributeName : [UIColor colorWithHexString:@"#333333"]};
        _segControl.selectedTitleTextAttributes = @{NSFontAttributeName : MK_FONT_PFSC_Medium(16),
                                                    NSForegroundColorAttributeName : [UIColor hex_9E6DFC]};
        
        _segControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationNone;
        _segControl.segmentWidthStyle = HMSegmentedControlSegmentWidthStyleDynamic;
        
        _segControl.selectionIndicatorHeight = 2.0f;
        _segControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
        _segControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
        _segControl.selectionIndicatorColor = [UIColor hex_9E6DFC];
        
        _segControl.segmentEdgeInset = UIEdgeInsetsMake(0, 10, 0, 10);
        
        MJWeakSelf
        _segControl.indexChangeBlock = ^(NSInteger index) {
            [weakSelf.tableView.mj_header beginRefreshing];
        };
        
    }
    return _segControl;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.pageSize = [NSNumber numberWithInt:20];
    self.pageNumb = [NSNumber numberWithInt:1];
    self.datasDict = [NSMutableDictionary new];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self setUI];
}
- (UITableView *)tableView{
    if (!_tableView) {
        UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, MK_SCREEN_SAVE_BOTTOM_HEIGHT)];
        footView.backgroundColor = UIColor.clearColor;
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = UIColor.whiteColor;
        _tableView.tableFooterView = footView;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 15.0, *)) {
            self.tableView.sectionHeaderTopPadding = 0;
        }
        
        [_tableView registerNib:[UINib nibWithNibName:@"TLMallListTableViewCell" bundle:nil] forCellReuseIdentifier:@"TLMallListTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"TLCategoryNovelTableViewCell" bundle:nil] forCellReuseIdentifier:@"TLCategoryNovelTableViewCell"];
        
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadLastData)];
        header.lastUpdatedTimeLabel.hidden = YES;
        _tableView.mj_header = header;

        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        _tableView.mj_footer.hidden = YES;
        
    }
    return _tableView;
}
- (void)loadLastData{
    self.pageNumb = [NSNumber numberWithInt:1];
//    self.datasDict = [NSMutableDictionary new];
//    [self.datasArray removeAllObjects];
    [self netWorkAction];
}
- (void)loadMoreData{
    self.pageNumb = [NSNumber numberWithInt:self.pageNumb.intValue+1];
    
    [self netWorkAction];
}
- (NSMutableArray *)datasArray {
    if (!_datasArray) {
        _datasArray = [[NSMutableArray alloc] init];
        
    }
    return _datasArray;
}
- (NSMutableDictionary *)datasDict{
    if (!_datasDict) {
        _datasDict = [NSMutableDictionary new];
        
        [_datasDict setObject:@[] forKey:@"shortWorks"];
        [_datasDict setObject:@[] forKey:@"longWorks"];
        
    }
    return _datasDict;
}
- (void)setUI{
    
    [self.view addSubview:self.segControl];
    [self.segControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(15);
        make.right.equalTo(self.view.mas_right).offset(-15);
        make.top.equalTo(self.view);
        make.height.mas_offset(40);
    }];
    
    UIView *noDataView = [TL_UIFactory view];
    self.noDataView = noDataView;
    noDataView.hidden = NO;
    [self.view addSubview:noDataView];
    
    UILabel *noDataLabel = [TL_UIFactory labelWithBackgroundColor:nil font:SYSTEM_FONT(15) textColor:kBlackColor];
    noDataLabel.text = WXLocalizedString(@"抱歉，没有找到相关结果，请重新搜索。");
    noDataLabel.preferredMaxLayoutWidth = kScreenWidth - 50.0 * 2;
    noDataLabel.numberOfLines = 0;
    noDataLabel.textAlignment = NSTextAlignmentCenter;
    [noDataView addSubview:noDataLabel];
    
    CGFloat textHeight = noDataLabel.w_textHeight;
    self.noDataViewHeight = textHeight + 2 * 40.0;
    
    [noDataLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(noDataView);
        make.width.mas_equalTo(noDataLabel.preferredMaxLayoutWidth);
        make.height.mas_equalTo(textHeight);
    }];
    
    [noDataView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.centerY.equalTo(self.view.mas_centerY);
        make.width.mas_equalTo(kScreenWidth);
        make.height.mas_equalTo(0.0);
    }];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.segControl.mas_bottom);
        make.left.bottom.right.equalTo(self.view);
    }];
    
//    self.tableView.hidden = YES;
}
- (void)searchWithText:(NSString *)text{
    if ([self.searchText isEqualToString:text]) {
        return;
    }
    self.searchText = text;
    
    [self.tableView.mj_header beginRefreshing];
    
}
- (void)netWorkAction{
    if (self.segControl.selectedSegmentIndex == 0) {
        
        [self networkForAll:self.searchText];
    }else{
        [self networkForNovel];
    }
}
- (void)showResultPage:(NSInteger)index{

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.segControl.selectedSegmentIndex==0) {
        
        if (indexPath.section==0) {
            //短文
            TLMallListTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TLMallListTableViewCell"];
            
            NSArray *dataA = self.datasDict[[self.datasDict allKeys][0]];
            
            if (indexPath.row<dataA.count) {
                
                TLMallChannelModel *model = [TLMallChannelModel mj_objectWithKeyValues:dataA[indexPath.row]];
            
                cell.model = model;
                
            }
            
            return cell;
        }else{
        
            TLCategoryNovelTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TLCategoryNovelTableViewCell"];
            
            NSArray *dataA = self.datasDict[[self.datasDict allKeys][1]];
            
            if (indexPath.row<dataA.count) {
                
                TLMallChannelModel *model = [TLMallChannelModel mj_objectWithKeyValues:dataA[indexPath.row]];
            
                cell.model = model;
                
            }
            
            return cell;
            
        }
        
    }else{
        
        if (self.segControl.selectedSegmentIndex==1) {
            //短文
            TLMallListTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TLMallListTableViewCell"];
            
            if (indexPath.row<self.datasArray.count) {
                
                TLMallChannelModel *model = [TLMallChannelModel mj_objectWithKeyValues:self.datasArray[indexPath.row]];
            
                cell.model = model;
            }
            
            return cell;
        }else{
        
            TLCategoryNovelTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TLCategoryNovelTableViewCell"];
            
            if (indexPath.row<self.datasArray.count) {
                
                TLMallChannelModel *model = [TLMallChannelModel mj_objectWithKeyValues:self.datasArray[indexPath.row]];
            
                cell.model = model;
                
            }
            
            return cell;
            
        }
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.segControl.selectedSegmentIndex==0) {
        
        if (indexPath.section==0) {
            return 155;
        }else{
            return 167;
        }
        
    }else if (self.segControl.selectedSegmentIndex==1){
        return 155;
    }else{
        return 167;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (self.segControl.selectedSegmentIndex == 0) {
        
        return 36;
    }else{
        return 0;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    TLMallChannelModel *model;
    
    if (self.segControl.selectedSegmentIndex == 0) {
        
        NSArray *dataA = self.datasDict[self.datasDict.allKeys[indexPath.section]];
        
        if (indexPath.row<dataA.count) {
            
            TLMallChannelModel *models = [TLMallChannelModel mj_objectWithKeyValues:dataA[indexPath.row]];
            
            model = models;
        }
        
    }else{
        
        TLMallChannelModel *models = [TLMallChannelModel mj_objectWithKeyValues:self.datasArray[indexPath.row]];
        
        if (indexPath.row<self.datasArray.count) {
            
            model = models;
        }
    }
    
    if ([model.worksType isEqualToString:@"0"]) {
        //短篇
        TLShortStoryViewController *vc = [TLShortStoryViewController new];
        vc.worksId = model.worksId;
        [[TL_ViewHelper getCurrentViewController].navigationController pushViewController:vc animated:YES];
    }else{
        //长篇
//        TL_BookMallDetailViewController *vc = [TL_BookMallDetailViewController new];
//        vc.book_id = [model.worksId intValue];
//        [[TL_ViewHelper getCurrentViewController].navigationController pushViewController:vc animated:YES];
    }
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (self.segControl.selectedSegmentIndex == 0) {
        return 1;
    }else{
        return 1;
    }
    
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.segControl.selectedSegmentIndex == 0) {
        if (section==0) {
            if (self.datasDict.allKeys.count>0) {
                
                NSArray *dataA = self.datasDict[self.datasDict.allKeys[0]];
                
                return dataA.count;
            }else{
                return 0;
            }
        }else{
            if (self.datasDict.allKeys.count>1) {
                NSArray *dataA = self.datasDict[self.datasDict.allKeys[1]];
                return dataA.count;
            }else{
                return 0;
            }
        }
    }else{
        return self.datasArray.count;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 26)];
    view.backgroundColor = [UIColor whiteColor];
    UILabel *labTitle = [[UILabel alloc] initWithFrame:CGRectMake(16, 0, 200, 40)];
    labTitle.textColor = [UIColor colorWithHexString:@"#999999"];
    labTitle.font = SYSTEM_FONT(14);
    [view addSubview:labTitle];
    
    UIButton *btnMore = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnMore setTitle:@"view all >" forState:UIControlStateNormal];
    [btnMore setTitleColor:[UIColor colorWithHexString:@"#999999"] forState:UIControlStateNormal];
    btnMore.titleLabel.font = SYSTEM_FONT(12);
    btnMore.frame = CGRectMake(SCREEN_WIDTH-70-27, 10, 70, 20);
    btnMore.tag = section;
    [btnMore addTarget:self action:@selector(btnMoreAction:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btnMore];
    
    if (section==0) {
        labTitle.text = @"Short Story";
    }else{
        labTitle.text = @"Novel";
    }
    
    if (self.segControl.selectedSegmentIndex==0) {
        return view;
    }else{
        return nil;
    }
}
- (void)btnMoreAction:(UIButton *)button{
    
    self.segControl.selectedSegmentIndex = button.tag + 1;
    
    [self.tableView.mj_header beginRefreshing];
    
}
- (void)networkForAll:(NSString *)keyword{
    
    NSDictionary *param = @{
        @"keyWords":keyword
    };
    
    [APIManager sendGetRequest:[APIURLManager queryOsWorksAll] parameters:param model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        if (success) {
            self.datasDict = requestModel.data;
            
            NSArray *dataA = self.datasDict[self.datasDict.allKeys[0]];
            NSArray *dataB = self.datasDict[self.datasDict.allKeys[1]];
            
            if (!dataA) {
                dataA = @[];
            }
            if (!dataB) {
                dataB = @[];
            }
            
            if (dataA.count==0) {
            
                self.noDataView.hidden = NO;
                self.tableView.hidden = YES;
                
            }else{
            
                self.noDataView.hidden = YES;
                self.tableView.hidden = NO;
                
            }
            
            [self.tableView reloadData];
            [self endFreshingAciton];
        }else{
            self.noDataView.hidden = NO;
            self.tableView.hidden = YES;
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        
    }];
    
}
- (void)networkForNovel{
    
    NSString *type = @"0";
    if (self.segControl.selectedSegmentIndex == 1) {
        type = @"0";
    }else{
        type = @"1";
    }
    
    NSDictionary *param = @{
        @"worksType":type,
        @"keyWords":self.searchText,
        @"pageNum":self.pageNumb,
        @"pageSize":self.pageSize
    };
    
    [APIManager sendGetRequest:[APIURLManager getCategoryQueryOsWorks] parameters:param model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        if (success) {
            
            NSArray *arr = requestModel.data[@"records"];
            [self.datasArray addObjectsFromArray:arr];

            if (arr.count<self.pageSize.intValue) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            [self.tableView reloadData];
        }

        [self endFreshingAciton];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [self endFreshingAciton];
    }];
    
}
- (void)endFreshingAciton{
    [self.tableView.mj_header endRefreshing];
    if (self.segControl.selectedSegmentIndex==0) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }else{
        [self.tableView.mj_footer endRefreshing];
    }
}
@end
